package com.bridge.applets.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.bridge.applets.config.AliyunOSSConfig;
import com.bridge.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Component
public class AliyunOSSUtil {

    public static String PRE_PATH_VIDEO="video";
    public static String PRE_PATH_FILE="files";
    public static String PRE_PATH_FILE_CSV="files/csv";

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;


    /**
     * 上传文件。
     *
     * @param file 需要上传的文件路径
     * @return 如果上传的文件是图片的话，会返回图片的"URL"，如果非图片的话会返回"非图片，不可预览。文件路径为：+文件路径"
     */
    public String upLoad(MultipartFile file,String preDir) {

        log.info("------OSS文件上传开始--------" + file.getName());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        String originalFilename = file.getOriginalFilename();
        String fileSubffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 设置文件路径和名称
        String fileUrl = aliyunOSSConfig.getPrePath()+"/"+preDir + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName())+fileSubffix;
        if(StringUtil.isEmpty(preDir)){
            fileUrl = aliyunOSSConfig.getPrePath()+ "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName())+fileSubffix;
        }
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOSSConfig.getEndpoint(), aliyunOSSConfig.getAccessKeyId(), aliyunOSSConfig.getAccessKeySecret());
        try {
            // 上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(aliyunOSSConfig.getBucketName(), fileUrl, file.getInputStream()));
            if (result != null) {
                log.info("------OSS文件上传成功------" + fileUrl);
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getErrorMessage());
        } catch (Exception e) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "https://"+aliyunOSSConfig.getBucketName()+"."+aliyunOSSConfig.getEndpoint()+"/"+fileUrl;
    }

    public String upLoadByName(MultipartFile file,String filePathName) {

        log.info("------OSS文件上传开始--------" + file.getName());
        // 设置文件路径和名称
        String fileUrl = aliyunOSSConfig.getPrePath()+"/"+filePathName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOSSConfig.getEndpoint(), aliyunOSSConfig.getAccessKeyId(), aliyunOSSConfig.getAccessKeySecret());
        try {
            // 上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(aliyunOSSConfig.getBucketName(), fileUrl, file.getInputStream()));
            if (result != null) {
                log.info("------OSS文件上传成功------" + fileUrl);
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getErrorMessage());
        } catch (Exception e) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "https://"+aliyunOSSConfig.getBucketName()+"."+aliyunOSSConfig.getEndpoint()+"/"+fileUrl;
    }


    /**
     * 通过文件名下载文件
     *
     * @param objectName    要下载的文件名
     * @param localFileName 本地要创建的文件名
     */
    public void downloadFile(String objectName, String localFileName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOSSConfig.getEndpoint(), aliyunOSSConfig.getAccessKeyId(), aliyunOSSConfig.getAccessKeySecret());
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(aliyunOSSConfig.getBucketName(), objectName), new File(localFileName));
        // 关闭OSSClient。
        ossClient.shutdown();
    }

}
